/*************************************************************************
	> File Name: thread.hpp
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/10/02 16:21
 ************************************************************************/

#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <cstdio>

typedef void*(*fun_t)(void*);

const int NAME_SIZE = 64;

class ThreadData
{
public:
    void *_args;
    std::string _name;
};

class Thread
{
public:
    Thread (int num, fun_t callback, void* args):_func(callback)
    {
        char nameBuffer[NAME_SIZE];
        snprintf(nameBuffer, sizeof nameBuffer, "Thread-%d", num);
        _name = nameBuffer;
        _tdata._args = args;
        _tdata._name = _name;
    }

    void start()
    {
        pthread_create(&_tid, nullptr, _func, (void*)&_tdata);
    }

    std::string name()
    {
        return _name;
    }

    void join()
    {
        pthread_join(_tid, nullptr);
    }
    
private:
    std::string _name;
    fun_t _func;
    ThreadData _tdata;
    pthread_t _tid;
};
